import { ref } from 'vue'
import { chatMsgInterface, messageInterface, useChatStore } from '@/stores/useChatStore'
import { MessageType, gptMessageRole } from '@/types/enum'
import { getChatGptMsg } from '@/apis/chat'
import { chatGptResponse } from '@/types/interfaces'
import { useUserStore } from '@/stores/useUserStore'
import { parseContent } from '@/utils/common'
// import { handleMoveToBottom } from '@/utils/common'

export function useChatGpt() {
  const userMessage = ref<string>('')

  const chatStore = useChatStore()
  const userStore = useUserStore()

  const messageListRef = ref<HTMLDivElement | null>(null)

  const isReceiving = ref<boolean>(true)

  const handleAddMessage = (Msg: string) => {
    const userMsg: chatMsgInterface = {
      name: userStore.getUserInfo().nickname,
      msg: Msg,
      id: new Date().getTime(),
      type: MessageType.User,
      isLoading: false
    }
    chatStore.addChatMsg(userMsg)
    const message: messageInterface = {
      role: gptMessageRole.user,
      content: Msg
    }
    // 首先要将Msg存储到messages中
    chatStore.addMessageList(message)
    const gptResponse: chatMsgInterface = {
      name: '编程喵',
      msg: '',
      id: new Date().getTime() + 1,
      type: MessageType.System,
      isLoading: true
    }
    chatStore.addChatMsg(gptResponse)
  }

  const getChatGptMsgParams = (): chatGptResponse => {
    const params: chatGptResponse = {
      messages: chatStore.getMessages(),
      user_id: userStore.getUserId()
    }
    return params
  }

  const handleReceiveChunkMessage = async () => {
    try {
      isReceiving.value = true
      let messageChunks = ''
      const params = getChatGptMsgParams()
      const messageGenerator = getChatGptMsg(params)
      for await (const message of messageGenerator) {
        if (message === 'done') {
          // 要将gpt的话添加到聊天记录中
          const systemMsg: messageInterface = {
            role: gptMessageRole.system,
            content: messageChunks
          }
          chatStore.addMessageList(systemMsg)
          break
        }
        const { content, chat_id } = parseContent(message)
        messageChunks += content
        chatStore.setChatGptFinalResponse(messageChunks, chat_id)
        if (messageListRef.value) {
          // handleMoveToBottom(messageListRef.value)
        }
        // console.log(messageChunks)
      }
    } catch (err) {
      console.log(err)
      chatStore.setChatGptFinalResponse('编程喵似乎出了点问题呢~让我们重新来过T_T', 0)
    } finally {
      isReceiving.value = false
    }
  }

  const handleSendUserMessage = async (Msg: string) => {
    handleAddMessage(Msg)
    await handleReceiveChunkMessage()
  }

  return {
    chatStore,
    userMessage,
    messageListRef,
    isReceiving,
    handleSendUserMessage,
    handleReceiveChunkMessage,
    handleAddMessage,
    getChatGptMsgParams
  }
}
